import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App () {
    const [data, setData] = useState({ list: [] });
    const [query, setQuery] = useState('');
    const [search, setSearch] = useState('');
    const [isLoading, setLoading] = useState(false);
    const [isError, setIsError] = useState(false);

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            setIsError(false);
            try {
                const res = await axios({ url: 'http://localhost:8888/' });
                setData({ list: res.data });
            } catch (error) {
                setIsError(true);
            } finally {
                setLoading(false);
            }
        };
        fetchData();

        return () => {
            // 返回的函数作用是清除上次hook带的负面影响
            console.log('unmout');
        };
    }, [search]);

    return (
        <div>
            <input value={query} onChange={(e) => setQuery(e.target.value)} type="text"/>
            <button onClick={() => setSearch(query)}>click</button>
            {
                isError && <div>Something went wrong ...</div>
            }
            {
                isLoading ? (
                    <div>Loading...</div>
                ) : (
                    <ul>
                        {
                            data.list.map((item, idx) => (
                                <li key={idx}>{item.name} - {item.age}</li>
                            ))
                        }
                    </ul>
                )
            }
        </div>
    );
}

export default App;
